<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/limh/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/limh/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/limh/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/limh/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/limh/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/limh/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/limh/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="教程,">










<meta name="description" content="PWM 在单片机中的应用是非常广泛的，它的基本原理很简单，但往往应用于不同场合上意义也不完全一样，这里我先把基本概念和基本原理给大家介绍一下，后边遇到用的时候起码知道是个什么东西。 PWM 是 Pulse Width Modulation 的缩写，它的中文名字是脉冲宽度调制，一种说法是它利用微处理器的数字输出来对模拟电路进行控制的一种有效的技术，其实就是使用数字信号达到一个模拟信号的效果。这是个什">
<meta name="keywords" content="教程">
<meta property="og:type" content="article">
<meta property="og:title" content="10.2、PWM的原理与控制程序">
<meta property="og:url" content="https://tdnr.gitee.io/limh/2014/12/01/mcu066/index.html">
<meta property="og:site_name" content="土逗牛肉">
<meta property="og:description" content="PWM 在单片机中的应用是非常广泛的，它的基本原理很简单，但往往应用于不同场合上意义也不完全一样，这里我先把基本概念和基本原理给大家介绍一下，后边遇到用的时候起码知道是个什么东西。 PWM 是 Pulse Width Modulation 的缩写，它的中文名字是脉冲宽度调制，一种说法是它利用微处理器的数字输出来对模拟电路进行控制的一种有效的技术，其实就是使用数字信号达到一个模拟信号的效果。这是个什">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://c.biancheng.net/cpp/uploads/allimg/140318/1-14031Q32Z0X1.png">
<meta property="og:updated_time" content="2019-01-27T05:03:56.165Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="10.2、PWM的原理与控制程序">
<meta name="twitter:description" content="PWM 在单片机中的应用是非常广泛的，它的基本原理很简单，但往往应用于不同场合上意义也不完全一样，这里我先把基本概念和基本原理给大家介绍一下，后边遇到用的时候起码知道是个什么东西。 PWM 是 Pulse Width Modulation 的缩写，它的中文名字是脉冲宽度调制，一种说法是它利用微处理器的数字输出来对模拟电路进行控制的一种有效的技术，其实就是使用数字信号达到一个模拟信号的效果。这是个什">
<meta name="twitter:image" content="http://c.biancheng.net/cpp/uploads/allimg/140318/1-14031Q32Z0X1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/limh/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tdnr.gitee.io/limh/2014/12/01/mcu066/">





  <title>10.2、PWM的原理与控制程序 | 土逗牛肉</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans ">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/limh/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">土逗牛肉</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/limh/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/limh/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/limh/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/limh/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/limh/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tdnr.gitee.io/limh/limh/2014/12/01/mcu066/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="土逗牛肉">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/limh/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="土逗牛肉">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">10.2、PWM的原理与控制程序</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2014-12-01T20:36:49+08:00">
                2014-12-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/limh/categories/单片机教程/" itemprop="url" rel="index">
                    <span itemprop="name">单片机教程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>PWM 在单片机中的应用是非常广泛的，它的基本原理很简单，但往往应用于不同场合上意义也不完全一样，这里我先把基本概念和基本原理给大家介绍一下，后边遇到用的时候起码知道是个什么东西。</p>
<p>PWM 是 Pulse Width Modulation 的缩写，它的中文名字是脉冲宽度调制，一种说法是它利用微处理器的数字输出来对模拟电路进行控制的一种有效的技术，其实就是使用数字信号达到一个模拟信号的效果。这是个什么概念呢？我们一步步来介绍。</p>
<p>首先从它的名字来看，脉冲宽度调制，就是改变脉冲宽度来实现不同的效果。我们先来看三组不同的脉冲信号，如图 10-1 所示。</p>
<p><img src="http://c.biancheng.net/cpp/uploads/allimg/140318/1-14031Q32Z0X1.png" alt></p>
<center><strong>图 10-1  PWM 波形</strong></center>

<p>这是一个周期是 10ms，即频率是 100Hz 的波形，但是每个周期内，高低电平脉冲宽度各不相同，这就是 PWM 的本质。在这里大家要记住一个概念，叫做“占空比”。占空比是指高电平的时间占整个周期的比例。比如第一部分波形的占空比是 40%，第二部分波形占空比是 60%，第三部分波形占空比是 80%，这就是 PWM 的解释。</p>
<p>那为何它能对模拟电路进行控制呢？大家想一想，我们数字电路里，只有 0 和 1 两种状态，比如我们第 2 章学会的点亮 LED 小灯那个程序，当我们写一个 LED = 0;小灯就会长亮，当我们写一个 LED = 1;小灯就会灭掉。当我们让小灯亮和灭间隔运行的时候，小灯是闪烁。</p>
<p>如果我们把这个间隔不断的减小，减小到我们的肉眼分辨不出来，也就是 100Hz 以上的频率，这个时候小灯表现出来的现象就是既保持亮的状态，但亮度又没有 LED = 0;时的亮度高。那我们不断改变时间参数，让 LED = 0;的时间大于或者小于 LED = 1;的时间，会发现亮度都不一样，这就是模拟电路的感觉了，不再是纯粹的 0 和 1，还有亮度不断变化。大家会发现，如果我们用 100Hz 的信号，如图 10-1 所示，假如高电平熄灭小灯，低电平点亮小灯的话，第一部分波形熄灭 4ms，点亮 6ms，亮度最高，第二部分熄灭 6ms，点亮 4ms，亮度次之，第三部分熄灭 8ms，点亮 2ms，亮度最低。那么用程序验证一下我们的理论，我们用定时器T0 定时改变 P0.0 的输出来实现 PWM，与纯定时不同的是，这里我们每周期内都要重载两次定时器初值，即用两个不同的初值来控制高低电平的不同持续时间。为了使亮度的变化更加明显，程序中使用的占空比差距更大。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">sbit PWMOUT = P0^0;</span><br><span class="line">sbit ADDR0 = P1^0;</span><br><span class="line">sbit ADDR1 = P1^1;</span><br><span class="line">sbit ADDR2 = P1^2;</span><br><span class="line">sbit ADDR3 = P1^3;</span><br><span class="line">sbit ENLED = P1^4;</span><br><span class="line">unsigned char HighRH = 0; //高电平重载值的高字节</span><br><span class="line">unsigned char HighRL = 0; //高电平重载值的低字节</span><br><span class="line">unsigned char LowRH = 0; //低电平重载值的高字节</span><br><span class="line">unsigned char LowRL = 0; //低电平重载值的低字节</span><br><span class="line">void ConfigPWM(unsigned int fr, unsigned char dc);</span><br><span class="line">void ClosePWM();</span><br><span class="line">void main()&#123;</span><br><span class="line">    unsigned int i;</span><br><span class="line">    EA = 1; //开总中断</span><br><span class="line">    ENLED = 0; //使能独立 LED</span><br><span class="line">    ADDR3 = 1;</span><br><span class="line">    ADDR2 = 1;</span><br><span class="line">    ADDR1 = 1;</span><br><span class="line">    ADDR0 = 0;</span><br><span class="line">   </span><br><span class="line">    while (1)&#123;</span><br><span class="line">        ConfigPWM(100, 10); //频率 100Hz，占空比 10%</span><br><span class="line">        for (i=0; i&lt;40000; i++);</span><br><span class="line">        ClosePWM();</span><br><span class="line">        ConfigPWM(100, 40); //频率 100Hz，占空比 40%</span><br><span class="line">        for (i=0; i&lt;40000; i++);</span><br><span class="line">        ClosePWM();</span><br><span class="line">        ConfigPWM(100, 90); //频率 100Hz，占空比 90%</span><br><span class="line">        for (i=0; i&lt;40000; i++);</span><br><span class="line">        ClosePWM(); //关闭 PWM，相当于占空比 100%</span><br><span class="line">        for (i=0; i&lt;40000; i++);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 配置并启动 PWM，fr-频率，dc-占空比 */</span><br><span class="line">void ConfigPWM(unsigned int fr, unsigned char dc)&#123;</span><br><span class="line">    unsigned int high, low;</span><br><span class="line">    unsigned long tmp;</span><br><span class="line">   </span><br><span class="line">    tmp = (11059200/12) / fr; //计算一个周期所需的计数值</span><br><span class="line">    high = (tmp*dc) / 100; //计算高电平所需的计数值</span><br><span class="line">    low = tmp - high; //计算低电平所需的计数值</span><br><span class="line">    high = 65536 - high + 12; //计算高电平的重载值并补偿中断延时</span><br><span class="line">    low = 65536 - low + 12;//计算低电平的重载值并补偿中断延时</span><br><span class="line">   </span><br><span class="line">    HighRH = (unsigned char)(high&gt;&gt;8); //高电平重载值拆分为高低字节</span><br><span class="line">    HighRL = (unsigned char)high;</span><br><span class="line">    LowRH = (unsigned char)(low&gt;&gt;8); //低电平重载值拆分为高低字节</span><br><span class="line">    LowRL = (unsigned char)low;</span><br><span class="line">   </span><br><span class="line">    TMOD &amp;= 0xF0; //清零 T0 的控制位</span><br><span class="line">    TMOD |= 0x01; //配置 T0 为模式 1</span><br><span class="line">    TH0 = HighRH; //加载 T0 重载值</span><br><span class="line">    TL0 = HighRL;</span><br><span class="line">    ET0 = 1; //使能 T0 中断</span><br><span class="line">    TR0 = 1; //启动 T0</span><br><span class="line">    PWMOUT = 1; //输出高电平</span><br><span class="line">&#125;</span><br><span class="line">/* 关闭 PWM */</span><br><span class="line">void ClosePWM()&#123;</span><br><span class="line">    TR0 = 0; //停止定时器</span><br><span class="line">    ET0 = 0; //禁止中断</span><br><span class="line">    PWMOUT = 1; //输出高电平</span><br><span class="line">&#125;</span><br><span class="line">/* T0 中断服务函数，产生 PWM 输出 */</span><br><span class="line">void InterruptTimer0() interrupt 1&#123;</span><br><span class="line">    if (PWMOUT == 1)&#123; //当前输出为高电平时，装载低电平值并输出低电平</span><br><span class="line">        TH0 = LowRH;</span><br><span class="line">        TL0 = LowRL;</span><br><span class="line">        PWMOUT = 0;</span><br><span class="line">    &#125;else&#123; //当前输出为低电平时，装载高电平值并输出高电平</span><br><span class="line">        TH0 = HighRH;</span><br><span class="line">        TL0 = HighRL;</span><br><span class="line">        PWMOUT = 1;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>需要提醒大家的是，由于标准 51 单片机中没有专门的 PWM 模块，所以我们用定时器加中断的方式来产生 PWM，而现在有很多的单片机都会集成硬件的 PWM 模块，这种情况下需要我们做的就仅仅是计算一下周期计数值和占空比计数值然后配置到相关的 SFR 中即可，既使程序得到了简化又确保了 PWM 的输出品质（因为消除了中断延时的影响）。</p>
<p>大家编译下载程序后，会发现小灯从最亮到灭一共 4 个亮度等级。如果我们让亮度等级更多，并且让亮度等级连续起来，会产生一个小灯渐变的效果，与呼吸有点类似，所以我们习惯上称之为呼吸灯，程序代码如下，这个程序用了 2 个定时器 2 个中断，这是我们第一次这样用，大家可以学习一下。我们来试试这个程序，试完了大家一定要能自己把程序写出来，切记。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">sbit PWMOUT = P0^0;</span><br><span class="line">sbit ADDR0 = P1^0;</span><br><span class="line">sbit ADDR1 = P1^1;</span><br><span class="line">sbit ADDR2 = P1^2;</span><br><span class="line">sbit ADDR3 = P1^3;</span><br><span class="line">sbit ENLED = P1^4;</span><br><span class="line">unsigned long PeriodCnt = 0; //PWM 周期计数值</span><br><span class="line">unsigned char HighRH = 0; //高电平重载值的高字节</span><br><span class="line">unsigned char HighRL = 0; //高电平重载值的低字节</span><br><span class="line">unsigned char LowRH = 0; //低电平重载值的高字节</span><br><span class="line">unsigned char LowRL = 0; //低电平重载值的低字节</span><br><span class="line">unsigned char T1RH = 0; //T1 重载值的高字节</span><br><span class="line">unsigned char T1RL = 0; //T1 重载值的低字节</span><br><span class="line">void ConfigTimer1(unsigned int ms);</span><br><span class="line">void ConfigPWM(unsigned int fr, unsigned char dc);</span><br><span class="line">void main()&#123;</span><br><span class="line">    EA = 1; //开总中断</span><br><span class="line">    ENLED = 0; //使能独立 LED</span><br><span class="line">    ADDR3 = 1;</span><br><span class="line">    ADDR2 = 1;</span><br><span class="line">    ADDR1 = 1;</span><br><span class="line">    ADDR0 = 0;</span><br><span class="line">   </span><br><span class="line">    ConfigPWM(100, 10); //配置并启动 PWM</span><br><span class="line">    ConfigTimer1(50); //用 T1 定时调整占空比</span><br><span class="line">    while (1);</span><br><span class="line">&#125;</span><br><span class="line">/* 配置并启动 T1，ms-定时时间 */</span><br><span class="line">void ConfigTimer1(unsigned int ms)&#123;</span><br><span class="line">    unsigned long tmp; //临时变量</span><br><span class="line">    tmp = 11059200 / 12; //定时器计数频率</span><br><span class="line">    tmp = (tmp * ms) / 1000; //计算所需的计数值</span><br><span class="line">    tmp = 65536 - tmp; //计算定时器重载值</span><br><span class="line">    tmp = tmp + 12; //补偿中断响应延时造成的误差</span><br><span class="line">    T1RH = (unsigned char)(tmp&gt;&gt;8); //定时器重载值拆分为高低字节</span><br><span class="line">    T1RL = (unsigned char)tmp;</span><br><span class="line">    TMOD &amp;= 0x0F; //清零 T1 的控制位</span><br><span class="line">    TMOD |= 0x10; //配置 T1 为模式 1</span><br><span class="line">    TH1 = T1RH; //加载 T1 重载值</span><br><span class="line">    TL1 = T1RL;</span><br><span class="line">    ET1 = 1; //使能 T1 中断</span><br><span class="line">    TR1 = 1; //启动 T1</span><br><span class="line">&#125;</span><br><span class="line">/* 配置并启动 PWM，fr-频率，dc-占空比 */</span><br><span class="line">void ConfigPWM(unsigned int fr, unsigned char dc)&#123;</span><br><span class="line">    unsigned int high, low;</span><br><span class="line">    PeriodCnt = (11059200/12) / fr; //计算一个周期所需的计数值</span><br><span class="line">    high = (PeriodCnt*dc) / 100; //计算高电平所需的计数值</span><br><span class="line">    low = PeriodCnt - high; //计算低电平所需的计数值</span><br><span class="line">    high = 65536 - high + 12; //计算高电平的定时器重载值并补偿中断延时</span><br><span class="line">    low = 65536 - low + 12; //计算低电平的定时器重载值并补偿中断延时</span><br><span class="line">    HighRH = (unsigned char)(high&gt;&gt;8); //高电平重载值拆分为高低字节</span><br><span class="line">    HighRL = (unsigned char)high;</span><br><span class="line">    LowRH = (unsigned char)(low&gt;&gt;8); //低电平重载值拆分为高低字节</span><br><span class="line">    LowRL = (unsigned char)low;</span><br><span class="line">   </span><br><span class="line">    TMOD &amp;= 0xF0; //清零 T0 的控制位</span><br><span class="line">    TMOD |= 0x01; //配置 T0 为模式 1</span><br><span class="line">    TH0 = HighRH; //加载 T0 重载值</span><br><span class="line">    TL0 = HighRL;</span><br><span class="line">    ET0 = 1; //使能 T0 中断</span><br><span class="line">    TR0 = 1; //启动 T0</span><br><span class="line">    PWMOUT = 1; //输出高电平</span><br><span class="line">&#125;</span><br><span class="line">/* 占空比调整函数，频率不变只调整占空比 */</span><br><span class="line">void AdjustDutyCycle(unsigned char dc)&#123;</span><br><span class="line">    unsigned int high, low;</span><br><span class="line">    high = (PeriodCnt*dc) / 100; //计算高电平所需的计数值</span><br><span class="line">    low = PeriodCnt - high; //计算低电平所需的计数值</span><br><span class="line">    high = 65536 - high + 12; //计算高电平的定时器重载值并补偿中断延时</span><br><span class="line">    low = 65536 - low + 12; //计算低电平的定时器重载值并补偿中断延时</span><br><span class="line">   </span><br><span class="line">    HighRH = (unsigned char)(high&gt;&gt;8); //高电平重载值拆分为高低字节</span><br><span class="line">    HighRL = (unsigned char)high;</span><br><span class="line">    LowRH = (unsigned char)(low&gt;&gt;8); //低电平重载值拆分为高低字节</span><br><span class="line">    LowRL = (unsigned char)low;</span><br><span class="line">&#125;</span><br><span class="line">/* T0 中断服务函数，产生 PWM 输出 */</span><br><span class="line">void InterruptTimer0() interrupt 1&#123;</span><br><span class="line">    if (PWMOUT == 1)&#123; //当前输出为高电平时，装载低电平值并输出低电平</span><br><span class="line">        TH0 = LowRH;</span><br><span class="line">        TL0 = LowRL;</span><br><span class="line">        PWMOUT = 0;</span><br><span class="line">    &#125;else&#123; //当前输出为低电平时，装载高电平值并输出高电平</span><br><span class="line">        TH0 = HighRH;</span><br><span class="line">        TL0 = HighRL;</span><br><span class="line">        PWMOUT = 1;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* T1 中断服务函数，定时动态调整占空比 */</span><br><span class="line">void InterruptTimer1() interrupt 3&#123;</span><br><span class="line">    static bit dir = 0;</span><br><span class="line">    static unsigned char index = 0;</span><br><span class="line">    unsigned char code table[13] = &#123; //占空比调整表</span><br><span class="line">        5, 18, 30, 41, 51, 60, 68, 75, 81, 86, 90, 93, 95</span><br><span class="line">    &#125;;</span><br><span class="line">   </span><br><span class="line">    TH1 = T1RH; //重新加载 T1 重载值</span><br><span class="line">    TL1 = T1RL;</span><br><span class="line">    AdjustDutyCycle(table[index]); //调整 PWM 的占空比</span><br><span class="line">    if (dir == 0)&#123; //逐步增大占空比</span><br><span class="line">        index++;</span><br><span class="line">        if (index &gt;= 12)&#123;</span><br><span class="line">            dir = 1;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;else&#123; //逐步减小占空比</span><br><span class="line">        index--;</span><br><span class="line">        if (index == 0)&#123;</span><br><span class="line">            dir = 0;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>呼吸灯效果做出来后，利用这个基本原理，其它各种效果的灯光闪烁都应该可以做出来，大家看到的 KTV 里边那绚丽的灯光闪烁，其实就是采用的 PWM 技术控制的。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/limh/tags/教程/" rel="tag"># 教程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/limh/2014/12/01/mcu065/" rel="next" title="10.1、单片机数字秒表程序">
                <i class="fa fa-chevron-left"></i> 10.1、单片机数字秒表程序
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/limh/2014/12/01/mcu067/" rel="prev" title="10.3、单片机交通灯实例">
                10.3、单片机交通灯实例 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/limh/images/avatar.jpg" alt="土逗牛肉">
            
              <p class="site-author-name" itemprop="name">土逗牛肉</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/limh/archives/">
              
                  <span class="site-state-item-count">255</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/limh/categories/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/limh/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/limhGeek" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:1591054297@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/f73b243e7cc9" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-user-circle-o"></i>简书</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">土逗牛肉</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
	var str = GetUrlParam('height');
    if (str === '0'){
		document.getElementById('header').style.display = 'none';
		document.getElementById('comments').style.display = 'none';
		document.getElementById('footer').style.display = 'none';
		document.getElementsByClassName('post-footer').item(0).style.display = 'none'
	}
	
    function GetUrlParam(paraName) {
        var url = document.location.toString();
        var arrObj = url.split("?");

        if (arrObj.length > 1) {
            var arrPara = arrObj[1].split("&");
            var arr;

            for (var i = 0; i < arrPara.length; i++) {
                 arr = arrPara[i].split("=");

                if (arr != null && arr[0] === paraName) {
                    return arr[1];
                }
            }
            return "";
        } else {
            return "";
        }
    }
</script>









  












  
  
    <script type="text/javascript" src="/limh/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/limh/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/limh/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/limh/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/limh/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/limh/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
